package org.example.springboot_dynamicdatasource.mybatisplugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.example.springboot_dynamicdatasource.dynamic.DynamicDatasource;
import org.springframework.stereotype.Component;

/**
 * 适用与读写分离的数据库架构
 */

//@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class DynamicDatasourcePlugin implements Interceptor {
    // 适用于读写分离的架构，在这里判断是查找还是更新数据设置threadlocal的值
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement arg = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = arg.getSqlCommandType();
        System.out.println("sqlCommandType.name() = " + sqlCommandType.name());
        if (SqlCommandType.UPDATE == sqlCommandType) {
            DynamicDatasource.dsType.set("w");
        }else {
            DynamicDatasource.dsType.set("r");
        }
        return invocation.proceed();
    }
}
